package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @Author haoye
 * @Date 2025/10/22 15:47
 */
@Service
public class WechatServiceImpl implements WechatService {

    //小程序ID
    @Value("${wechat.appid}")
    private String appId;

    //小程序密钥
    @Value("${wechat.appSecret}")
    private String appSecret;

    private static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    private Map<String, Object> getCommonParamMap() {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", appId); // 小程序appid
        paramMap.put("secret", appSecret); // 小程序密钥
        return paramMap;
    }


    /**
     * 获取微信唯一身份标识openid
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        Map<String, Object> paramMap = this.getCommonParamMap();
        paramMap.put("js_code", code); // 临时授权码
        paramMap.put("grant_type", "authorization_code");
        String responseBody = HttpUtil.get(OPENID_URL, paramMap);
        return responseBody;
    }

    /**
     * 获取接口访问凭证
     * @return
     */
    private String getAccessToken() {
        Map<String, Object> paramMap = this.getCommonParamMap();
        paramMap.put("grant_type", "client_credential");
        String responseBody = HttpUtil.get(ACCESS_TOKEN_URL, paramMap);
        if (StrUtil.isBlank(responseBody)) {
            throw new BaseException("获取access_token失败");
        }
        JSONObject jsonObject = JSONUtil.parseObj(responseBody);
        return jsonObject.getStr("access_token");
    }

    /**
     * 获取微信用户的手机号
     *
     * @param code
     * @return
     */
    @Override
    public String getPhoneNum(String code) {
        String requestBody = JSONUtil.toJsonStr(Map.of("code", code));
        String responseBody = HttpUtil.post(PHONE_URL + getAccessToken(), requestBody);
        if (StrUtil.isBlank(responseBody)) {
            throw new BaseException("获取phoneInfo失败");
        }
        JSONObject jsonObject = JSONUtil.parseObj(responseBody);
        String phoneInfoJSON = jsonObject.getStr("phone_info");
        if (StrUtil.isBlank(phoneInfoJSON)) {
            throw new BaseException("获取phoneNumber失败");
        }
        JSONObject phoneNumberJSON = JSONUtil.parseObj(phoneInfoJSON);
        return phoneNumberJSON.getStr("phoneNumber");
    }
}
